//
//  YYEAcountManaViewController.m
//  YuYingEDU
//
//  Created by 胡波 on 2018/1/9.
//  Copyright © 2018年 胡波. All rights reserved.
//

#import "YYEAcountManaViewController.h"
#import "YYEAcountHeaderCell.h"
//#import "YYEAcountPhoneCell.h"
#import "YYEAcountContentCell.h"
#import "BRDatePickerView.h"
#import "BRStringPickerView.h"
#import "NSDate+BRAdd.h"
#import "NSStringExt.h"


@interface YYEAcountManaViewController () <UITableViewDelegate,UITableViewDataSource,UIImagePickerControllerDelegate,UINavigationControllerDelegate>

@property (nonatomic,strong) YYEBaseTableView  *tableview;
@property (nonatomic,strong) LoginModel *model;
@property (nonatomic,strong) UIImageView *headerIV;

@end

@implementation YYEAcountManaViewController

static NSString *headerCell = @"headerCell";
static NSString *contentCell = @"contentCell";
- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
    self.title = @"账户管理";
    
    self.view.backgroundColor = GeneralBackColor;
    
    LoginModel *model = [InfoCache unarchiveObjectWithFile:Person];
    self.model = model;
    
    [self configNavi];
    
    [self configUI];
    
    
}


- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    

    if (@available(iOS 11.0, *)) {
        UIScrollView.appearance.contentInsetAdjustmentBehavior = UIScrollViewContentInsetAdjustmentAlways;
    } else {
        // Fallback on earlier versions
    }
}

- (void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];
    

    if (@available(iOS 11.0, *)) {
        UIScrollView.appearance.contentInsetAdjustmentBehavior = UIScrollViewContentInsetAdjustmentNever;
    } else {
        // Fallback on earlier versions
    }

    
}

- (void)configNavi {
    
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc]initWithTitle:@"保存" style:UIBarButtonItemStyleDone target:self action:@selector(saveClicked)];
    [self.navigationItem.rightBarButtonItem setTintColor:[UIColor blackColor]];
    
}

- (void)configUI {
    
    [self.view addSubview:self.tableview];
    
    self.tableview.backgroundColor = GeneralBackColor;
    self.tableview.separatorStyle = UITableViewCellSeparatorStyleNone;
    [self.tableview registerClass:[YYEAcountHeaderCell class] forCellReuseIdentifier:headerCell];
    [self.tableview registerClass:[YYEAcountContentCell class] forCellReuseIdentifier:contentCell];
    
    [self.tableview makeConstraints:^(MASConstraintMaker *make) {
        make.edges.equalTo(UIEdgeInsetsZero);
    }];
    
}

- (YYEBaseTableView *)tableview {
    
    if (!_tableview) {
        _tableview = [[YYEBaseTableView alloc]initwithDelegate:self];
    }
    return _tableview;
    
}

- (void)editingChanged:(UITextField *)tf
{
    if (tf.tag == 100) {
        
        _model.name = tf.text;
    }
    else {
        _model.credid = tf.text;

    }
}

#pragma mark -- UITableview
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    
    return 3;
    
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    
    if (section == 2) {
        return 5;
    }else {
        return 1;
    }
    
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    if (indexPath.section == 0) {
        
        YYEAcountHeaderCell *cell = [tableView dequeueReusableCellWithIdentifier:headerCell];
        
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        self.headerIV = cell.headerIV;
        [self.headerIV sd_setImageWithURL:[NSURL URLWithString:_model.img] placeholderImage:[UIImage imageNamed:@"headerHolder"]];
        return cell;
        
    }else if (indexPath.section == 1) {
        
        YYEAcountContentCell *cell = [tableView dequeueReusableCellWithIdentifier:contentCell];
        
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        cell.rightTF.hidden = YES;
        cell.nameLabel.text = @"手机号";
        cell.rightLabel.text = _model.username;
        
        return cell;
        
    }else {
        
        YYEAcountContentCell *cell = [tableView dequeueReusableCellWithIdentifier:contentCell];
        
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        
        NSArray *names = @[@"姓名",@"身份证",@"生日",@"性别",@"学历"];
        cell.nameLabel.text = names[indexPath.row];
        
        if (indexPath.row == 0) {
            
            cell.rightLabel.hidden = YES;
            cell.rightTF.placeholder = @"请输入姓名";
            cell.rightTF.text = _model.name;
            cell.rightTF.tag = 100;
            [cell.rightTF addTarget:self action:@selector(editingChanged:) forControlEvents:UIControlEventEditingChanged];
            
        }else if (indexPath.row == 1) {
            
            cell.rightLabel.hidden = YES;
            cell.rightTF.placeholder = @"请输入身份证号码";
            cell.rightTF.text = _model.credid;
            cell.rightTF.tag = 101;
            [cell.rightTF addTarget:self action:@selector(editingChanged:) forControlEvents:UIControlEventValueChanged];

        }else if (indexPath.row == 2) {
            
            cell.rightLabel.text = @"请选择生日";
            cell.rightTF.hidden = YES;
            
            if (_model.birth.length > 0) {
                cell.rightLabel.text = _model.birth;

            }

            
        }else if (indexPath.row == 3) {
            
            cell.rightLabel.text = @"请选择性别";
            cell.rightTF.hidden = YES;

            if (_model.sex.length > 0) {
                cell.rightLabel.text = _model.sex;

            }
            
        }else if (indexPath.row == 4) {
            
            cell.rightLabel.text = @"请选择学历";
            cell.rightTF.hidden = YES;

            if (_model.degree.length > 0) {
                cell.rightLabel.text = _model.degree;

            }
        }
        
        return cell;
        
    }
    
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    
    //获取单元格
    __block YYEAcountContentCell *cell = (YYEAcountContentCell *)[tableView cellForRowAtIndexPath:indexPath];
    
    if (indexPath.section == 0) {
        
        [self choosePhone];
        
    }
    if (indexPath.section == 2) {
        
        if (indexPath.row == 2) {
            
            NSString *birth = nil;
            if (![cell.rightLabel.text isEqualToString:@"请选择生日"]) {
                birth = cell.rightLabel.text;
            }

            [BRDatePickerView showDatePickerWithTitle:@"出生年月" dateType:UIDatePickerModeDate defaultSelValue:birth minDateStr:@"" maxDateStr:[NSDate currentDateString] isAutoSelect:YES resultBlock:^(NSString *selectValue) {
                cell.rightLabel.text = selectValue;
                _model.birth = selectValue;
            }];
        }
        
        if (indexPath.row == 3) {
            
            [BRStringPickerView showStringPickerWithTitle:@"" dataSource:@[@"男", @"女"] defaultSelValue:@"男" isAutoSelect:YES resultBlock:^(id selectValue) {
                cell.rightLabel.text = selectValue;
                _model.sex = selectValue;

            }];
        }
        
        if (indexPath.row == 4) {
            
            [BRStringPickerView showStringPickerWithTitle:@"学历" dataSource:@[@"大专以下", @"大专", @"本科", @"硕士", @"博士", @"博士后"] defaultSelValue:@"本科" isAutoSelect:YES resultBlock:^(id selectValue) {
                cell.rightLabel.text = selectValue;
                _model.degree  = selectValue;

            }];
        }
        
    }
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    if (indexPath.section == 0) {
        return 70;
    }else {
        return 55;
    }
    
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    
    return 10;
    
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
    
    UIView *contentView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, 10)];
    contentView.backgroundColor = GeneralBackColor;
    
    return contentView;
    
}

// 保存
- (void)saveClicked {
    
    if (self.model.credid.length < 1) {
        
        [self.view makeToast:@"请输入身份证号码"];
        
        
    }else if (self.model.name.length < 1) {
        
        [self.view makeToast:@"请输入姓名"];
        
        
    } else {
        
        if (![NSString checkUserIDCard:self.model.credid]) {
            
            [self.view makeToast:@"非法身份证号"];
            return;
            
        }
        
        NSDictionary *dic = @{
                              @"name":self.model.name,
                              @"username":self.model.username,
                              @"credid":self.model.credid,
                              @"birth":self.model.birth,
                              @"sex":self.model.sex,
                              @"degree":self.model.degree,
                              @"token":[LoginModel shareLogin].token
                              };
        NSLog(@" %@ ",dic);
        [SVProgressHUD show];
        [AFNHelper post:WriteUserInfo parameters:dic constructingBodyWithBlock:^(id<AFMultipartFormData> formData) {
            
            [formData appendPartWithFileData:UIImageJPEGRepresentation(self.headerIV.image, 0.3)
                                        name:@"img"
                                    fileName:@"header.png"
                                    mimeType:@"image/png"];
            
        } success:^(id responseObject) {
            
            NSLog(@"%@",responseObject);

            if ([responseObject[@"status"] isEqual:@1]) {
                PersonModel *model = [PersonModel yy_modelWithJSON:responseObject[@"data"][@"userinfo"]];
                [InfoCache archiveObject:model toFile:Person];
                [self.navigationController popViewControllerAnimated:YES];
            }
            [SVProgressHUD showWithStatus:responseObject[@"message"]];
            [SVProgressHUD dismiss];
            
        } faliure:^(id error) {
            
            NSLog(@"请求失败");
            [SVProgressHUD showWithStatus:ShowError];
            [SVProgressHUD dismissWithDelay:0.5];
            
        }];
    }
    
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (void)choosePhone {
    
    UIImagePickerController *pickerVC = [[UIImagePickerController alloc]init];
    pickerVC.delegate = self;
    //    pickerVC.allowsEditing = NO;
    
    UIAlertController *alertVC = [UIAlertController alertControllerWithTitle:nil message:nil preferredStyle:UIAlertControllerStyleActionSheet];
    UIAlertAction *cameraAction = [UIAlertAction actionWithTitle:@"手机拍摄" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        
        pickerVC.sourceType = UIImagePickerControllerSourceTypeCamera;
        //        pickerVC.cameraDevice = UIImagePickerControllerCameraDeviceFront;
        [self presentViewController:pickerVC animated:YES completion:nil];
        
    }];
    
    UIAlertAction *photosAction = [UIAlertAction actionWithTitle:@"相册选择" style:UIAlertActionStyleDestructive handler:^(UIAlertAction * _Nonnull action) {
        
        pickerVC.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
        [self presentViewController:pickerVC animated:YES completion:nil];
        
    }];
    
    UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
        
    }];
    
    if ([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera]) {
        
        [alertVC addAction:cameraAction];
        
    }
    [alertVC addAction:photosAction];
    [alertVC addAction:cancelAction];
    [self presentViewController:alertVC animated:YES completion:nil];
    
}

#pragma mark -- UIImagepickerDelegate
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary<NSString *,id> *)info {
    
    [picker dismissViewControllerAnimated:YES completion:nil];
    
    UIImage *image = [info objectForKey:UIImagePickerControllerOriginalImage];
    self.headerIV.image = image;
    
}

- (void)imagePickerControllerDidCancel:(UIImagePickerController *)picker {
    
    [self dismissViewControllerAnimated:YES completion:nil];
    
}

@end
